package com.hu.system.service.impl;

import java.util.List;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.hu.common.utils.SecurityUtils;
import com.hu.system.mapper.StockRecordMapper;
import com.hu.system.mapper.SysUserShopMapper;
import com.hu.system.domain.StockRecord;
import com.hu.system.service.IStockRecordService;

/**
 * 库存记录Service业务层处理
 *
 * @author hu
 * @date 2025-01-22
 */
@Service
public class StockRecordServiceImpl implements IStockRecordService {
    @Autowired
    private StockRecordMapper stockRecordMapper;

    @Autowired
    private SysUserShopMapper userShopMapper;

    /**
     * 查询库存记录列表（合并入库和出库）
     *
     * @param stockRecord 库存记录
     * @return 库存记录
     */
    @Override
    public List<StockRecord> selectStockRecordList(StockRecord stockRecord) {
        Long userId = SecurityUtils.getUserId();

        // 管理员查看全部
        if (userId != null && userId == 1L) {
            return stockRecordMapper.selectStockRecordList(stockRecord);
        }

        // 普通用户根据店铺过滤
        // 保存分页参数
        com.github.pagehelper.Page<?> originalPage = com.github.pagehelper.PageHelper.getLocalPage();
        Integer originalPageNum = originalPage != null ? originalPage.getPageNum() : null;
        Integer originalPageSize = originalPage != null ? originalPage.getPageSize() : null;

        // 清除分页参数避免影响店铺查询
        PageHelper.clearPage();
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);

        // 恢复分页参数
        if (originalPageNum != null && originalPageSize != null) {
            PageHelper.startPage(originalPageNum, originalPageSize);
        }

        if (shopIds == null || shopIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 设置店铺ID过滤条件（支持多店铺）
        stockRecord.getParams().put("shopIdList", shopIds);

        return stockRecordMapper.selectStockRecordList(stockRecord);
    }
}

